#!/bin/bash -eu
#
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This script runs for about 3-4 minutes - it is time that is required to load
# Alfresco webapps on Tomcat

source /opt/c2d/c2d-utils || exit 1

postgresql_alfresco_password="$(get_attribute_value "postgresql-alfresco-password")"
alfresco_admin_password="$(get_attribute_value "alfresco-admin-password")"

declare -r postgresql_alfresco_password
declare -r alfresco_admin_password

# Change PostgreSQL alfresco user password and update Alfresco configuration
su - postgres -c "psql -c \"alter role alfresco with password '${postgresql_alfresco_password}'\""
export POSTGRESQL_ALFRESCO_PASSWORD=${postgresql_alfresco_password}
envsubst \
  < /opt/alfresco/alfresco-global.properties.template \
  > /opt/alfresco/tomcat/shared/classes/alfresco-global.properties
rm /opt/alfresco/alfresco-global.properties.template

# Add hostname entries to /etc/hosts
echo "127.0.0.1 $(hostname)" >> /etc/hosts
echo "::1 $(hostname)" >> /etc/hosts

# Enable Alfresco to be automatically started on boot
systemctl enable alfresco

# Start Alfresco
service alfresco start

# After re/starting Alfresco, wait until Tomcat responds to Alfresco Share requests.
until curl --output /dev/null --silent --head --fail -m 10 http://localhost:8080/share; do
  sleep 5
done

# Change default admin user password in Alfresco
curl -X POST http://localhost:8080/alfresco/service/api/person/changepassword/admin \
  --user admin:admin \
  --header "Content-type: application/json" \
  -d "{ newpw: '${alfresco_admin_password}', oldpw: 'admin' }"